#include <iostream>
#include <zlib.h>
#include <string>
#include <random>
using namespace std;
void readfastq(char *fq1, char *fq2, char *outfq1, char *outfq2, float random_ratio);

int main(int args, char *argv[]) {
    std::cout << "usage: randomReads inputfq1.gz inputfq2.gz outputfq1.gz outputfq2.gz ratio(0.0-1.0) " << std::endl;
    char *fq1 = argv[1];
    char *fq2 = argv[2];
    char *fq3 = argv[3];
    char *fq4 = argv[4];
    float random_ratio = atof(argv[5]);
    readfastq(fq1, fq2, fq3, fq4, random_ratio);
    return 0;
}



void readfastq(char *fq1, char *fq2, char *outfq1, char *outfq2, float random_ratio) {
    gzFile fpgz1 = gzopen(fq1, "rb");
    gzFile fpgz2 = gzopen(fq2, "rb");
    gzFile fogz1 = gzopen(outfq1, "wb");
    gzFile fogz2 = gzopen(outfq2, "wb");
    char line1[512];
    memset(line1, 0, sizeof(line1));
    char line2[512];
    memset(line2, 0, sizeof(line2));
    int64_t count = 0;
    string lineout1 = "";
    string lineout2 = "";
    float random_num = 0.0;
    std::random_device rd;
    std::mt19937 gen32(rd());
    std::uniform_int_distribution<> dis(0,99);
    while (gzgets(fpgz1, line1, sizeof(line1)), gzgets(fpgz2, line2, sizeof(line2))) {
        count += 1;
        string line1_str, line2_str;
        line1_str = line1;
        line2_str = line2;
        if (count == 1) {
            lineout1 = line1_str;
            lineout2 = line2_str;
        } else if (count == 2) {
            lineout1 += line1_str;
            lineout2 += line2_str;
        } else if (count == 3) {
            lineout1 += line1_str;
            lineout2 += line2_str;
        } else if (count == 4) {
            lineout1 += line1_str;
            lineout2 += line2_str;
            count = 0;
            //cout << lineout1.c_str() << endl;
            int32_t num = dis(gen32);
            random_num = num / 100.0;
            if (random_num <= random_ratio) {
                gzwrite(fogz1, lineout1.c_str(), strlen(lineout1.c_str()));//这里需要转换成c_str写入gz文件才不会乱码
                gzwrite(fogz2, lineout2.c_str(), strlen(lineout2.c_str()));
                lineout1 = "";
                lineout2 = "";
                count = 0;
            }
        }
    }
    gzclose(fpgz1);
    gzclose(fpgz2);
    gzclose(fogz1);
    gzclose(fogz2);
}
